<template>
  <div class="warpper">
    <div class="toolbar">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" label-width="auto" label-position="right">
        <el-form-item label="Order Number">
          <el-input v-model="searchForm.ordernumber" @keyup.enter.native="search" placeholder="Enter NO">
          </el-input>
        </el-form-item>

        <el-form-item label="Status" prop="status">
          <el-select v-model="searchForm.status" placeholder="Select Status">
            <el-option v-for="item in status" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="Creator" prop="staff" style="margin-left: 24px;">
          <el-select v-model="searchForm.staff" placeholder="Select Staff">
            <el-option v-for="item in staff" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="Warehouse" prop="warehouse">
          <el-select v-model="searchForm.warehouse_id" placeholder="Select Warehouse" style="margin-left: 26px;">
            <el-option v-for="item in warehouse" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <br />

        <el-form-item label="Product">
          <el-input v-model="searchForm.productname" placeholder="Enter Product Name">
          </el-input>
        </el-form-item>
        <el-form-item label="Supplier" prop="supplier_id">
          <el-select v-model="searchForm.supplier_id" placeholder="Select Supplier">
            <el-option v-for="item in suppliers" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="Created Time" prop="created_at" style="margin-left: 24px;">
          <el-date-picker v-model="searchForm.created_at" type="datetimerange" range-separator="-"
            start-placeholder="Select Start Date" end-placeholder="Select End Date" value-format="yyyy-MM-dd"
            style="width: 140.7%;">
          </el-date-picker>
        </el-form-item>
        <br />
        <el-form-item>
          <el-button @click="find()" plain style="margin-left: 24px;">Search</el-button>
          <el-button type="primary" v-permission="['purchaseorders.store']" plain @click="stockinadd()">+
            New</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table">

      <el-table :data="tableData" size="small" stripe border style="width: 100%" align="center">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="ordernumber" label="Order Number" min-width="120" align="center" sortable />

        <el-table-column prop="totalqty" label="Product Quantity" width="160" align="center" sortable>
          <template v-slot="scope">
            <span>{{scope.row.totalqty}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalamount" label="Total Cast" width="110" align="center" sortable>
          <template v-slot="scope">
            <span>{{scope.row.totalamount}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="suppliername" label="Supplier" width="190" align="center" sortable>
          <template v-slot="scope">
            <span>{{scope.row.suppliername}}</span>
          </template>
        </el-table-column>

        <el-table-column label="warename" width="140" align="center">
          <template v-slot="scope">
            <span>{{scope.row.warename}}</span>
          </template>
        </el-table-column>

        <el-table-column prop="review_time" label="Review time" width="140" sortable />

        <el-table-column prop="reviewer" label="Reviewer" width="100" />

        <el-table-column prop="created_at" label="Created Time" min-width="120" sortable>
          <template v-slot="scope">
            <span>{{ scope.row.created_at | showDateTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="staff" width="144" align="center">
          <template v-slot="scope">
            <span>{{scope.row.staff}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="Status" width="100" sortable />
        <el-table-column label="Actions" width="100">
          <template slot-scope="scope">
            <el-button size="mini" v-permission="['purchaseorders.show']" plain
              @click="edit(scope.row.id)">View</el-button>
          </template>
        </el-table-column>
      </el-table>


    </div>
    <div class="page">
      <el-pagination v-if="isPaginate" background :current-page="page.current_page" :page-sizes="page.sizes"
        :page-size="page.per_page" layout="prev, pager, next" :total="page.total" @size-change="sizeChange"
        @current-change="currentChange" />
    </div>

  </div>
</template>

<script>
  import CURD from "@/mixin/CURD";
  import {
    index as warehouselist
  } from "@/api/warehouse";
  import {
    index as adminindex
  } from "@/api/admin";
  import {
    index as superindex
  } from "@/api/supplier";
  export default {
    name: "purchaseorderIndex",
    mixins: [CURD],
    components: {},
    data() {
      return {
        suppliers: [],
        formData: {},
        staff: [{
          id: null,
          name: "All",
        }],
        status: [{
            id: null,
            name: "All",
          },
          {
            id: "pending",
            name: "pending",
          }, {
            id: "approved",
            name: "approved",
          },
          {
            id: "rejection",
            name: "rejection",
          },
          {
            id: "voided",
            name: "voided",
          }
        ],
        module: "purchaseorder",
        newTitle: "New purchaseorder",
        editTitle: "Edit purchaseorder",
        isPaginate: true,
        isUploadFile: false,
        isShow: false,
        imageUrl: "",
        warehouse: [],
        deptOptions: [],
        searchForm: {

        },
      };
    },
    async created() {
      try {
        const {
          data
        } = await superindex(1, 100); // 假设index是一个异步函数
        this.suppliers = data;
      } catch (error) {
        console.error('Failed to fetch warehouse:', error);
      }
      try {
        const {
          data
        } = await warehouselist(1, 100); // 假设index是一个异步函数
        this.warehouse = data;
        this.warehouse.unshift({
          id: null,
          name: "All"
        })
      } catch (error) {
        console.error('Failed to fetch warehouse:', error);
      }

      try {
        const {
          data
        } = await adminindex(1, 100, {
          usertype: 1
        });
        this.staff = data.map(item => ({
          id: item.nickname, // 将 nickname 的值赋给 id
          name: item.nickname // 将 nickname 的值赋给 name
        }));

        // 在数组最前面添加一个特定的对象
        this.staff.unshift({
          id: null,
          name: 'ALL'
        });
      } catch (error) {
        console.error('Failed to fetch staff:', error);
      }
    },
    methods: {
      stockinadd() {
        this.$router.push({
          path: '/purchaseorder/purchaseorderadd',
          query: {
            id: null
          }
        })
      },
      edit(id) {
        this.$router.push({
          path: '/purchaseorder/editpurchaseorder',
          query: {
            id: id
          }
        })
      },
      onOpen(id) { // 展开
        this.currentOpen = id;
      },
      onClose(id) { // 关闭
        if (this.currentOpen === id) {
          this.currentOpen = null;
        }
      },
      getStatusColor(zt) { // 状态颜色
        if (zt === 'Normal') {
          return 'green-text';
        } else if (zt === 'Hidden') {
          return 'red-text';
        } else {
          return 'green-text';
        }
      },
      normalizer(node) {
        if (node.children && node.children.length === 0) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.name,
          children: node.children
        };
      },
      handleTree(data, id, parentId, children) {
        let config = {
          id: id || 'id',
          parentId: parentId || 'parentId',
          childrenList: children || 'children'
        };

        var childrenListMap = {};
        var nodeIds = {};
        var tree = [];

        for (let d of data) {
          let parentId = d[config.parentId];
          if (childrenListMap[parentId] == null) {
            childrenListMap[parentId] = [];
          }
          nodeIds[d[config.id]] = d;
          childrenListMap[parentId].push(d);
        }

        for (let d of data) {
          let parentId = d[config.parentId];
          if (nodeIds[parentId] == null) {
            tree.push(d);
          }
        }

        for (let t of tree) {
          adaptToChildrenList(t);
        }

        function adaptToChildrenList(o) {
          if (childrenListMap[o[config.id]] !== null) {
            o[config.childrenList] = childrenListMap[o[config.id]];
          }
          if (o[config.childrenList]) {
            for (let c of o[config.childrenList]) {
              adaptToChildrenList(c);
            }
          }
        }
        return tree;
      },
      adjustOrder(row) {
        row.isEdit = true;
      },
      async saveOrder(row) {
        let data = {
          id: row.id,
          order: row.order,
          action: "order"
        };
        row.isEdit = false;
        let {
          info
        } = await update(data);
        this.fetchData();
      },
      transfromData(data) {
        let result = data.map((item) => {
          item.isEdit = false;
          return item;
        });
        return result;
      },
      saveHandle(form) {
        this.$refs[form].validate(async (valid) => {
          if (valid) {
            if (this.isUploadFile) {
              // 更改了图片，则必须先传图片
              this.$refs.uploadAvatar.submit();
            } else {
              this.save(form);
            }
          } else {
            this.$message.error("Data filling error, please fill in again according to the requirements");
          }
        });
      },
      async save(form) {
        this.$refs[form].validate(async (valid) => {
          if (valid) {
            try {
              this.formData.suppliers = this.formData.suppliersdata.toString();
              if (this.isEdit) {
                let {
                  update
                } = require(`@/api/${this.module}`);
                let {
                  info
                } = await update(this.formData);
                this.$message.success("Edit successfully");
              }
              if (this.isNew) {
                let {
                  store
                } = require(`@/api/${this.module}`);

                let {
                  info
                } = await store(this.formData);
                this.$message.success("Save successfully");
              }
              this.fetchData();
              this.isEdit = false;
              this.isNew = false;
              this.dialogFormVisible = false;
            } catch (error) {
              let result = error.response.data;
              this.$message.error(result.info);
            }
          } else {
            this.$message.error("Data verification error, please input according to the specified rules");
            return false;
          }
        });
      },
      async avatarUpload(options) {
        const file = options.file;
        if (file) {
          this.fileReader.readAsDataURL(file);
        }
        this.fileReader.onload = async () => {
          const formData = new FormData();
          formData.append("file", file);
          uploadImg(formData)
            .then((res) => {
              const {
                data
              } = res;
              this.formData.image = data.url;
              this.save("ruleForm");
            })
            .catch((err) => {
              options.onError(err);
            });
        };
      },
      changeAvatar(file, fileList) {
        const reader = new window.FileReader();
        reader.readAsDataURL(new Blob([file.raw]));
        reader.onload = (e) => {
          this.formData.image = reader.result;
          this.imageUrl = reader.result;
          this.isUploadFile = true;
        };
      },
      async changeStatus(row) {
        let tips = "";
        if (row.status) {
          tips = "是否启用该文章?";
        } else {
          tips = "是否禁用该文章?";
        }
        this.$confirm(tips, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(async () => {
            let data = {
              id: row.id,
              status: row.status,
              action: "status"
            };
            let {
              info
            } = await update(data);
            this.$message.success(info);
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "Cancelled deletion"
            });
          });
      }
    }
  }
</script>
<style>
  .customWidth {
    width: 80%;
  }
</style>
<style>
  .table,
  .toolbar,
  .page {
    margin: 20px;
  }

  .toolbar {
    margin-top: 10px;
    padding: 5px;
  }

  .table {
    margin-bottom: 10px;
  }

  .page {
    margin-top: 10px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 78px;
    height: 78px;
    line-height: 78px;
    text-align: center;
  }

  .green-text {
    color: green;
  }

  .red-text {
    color: red;
  }

  .yellow-text {
    color: yellow;
  }
</style>
